package net.huashitong.user.service;

import java.util.UUID;

import net.huashitong.user.entity.SecurityToken;
import net.huashitong.user.entity.SysValid;
import net.huashitong.user.filter.LoginFilter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sirdc.modules.core.exceptions.ServiceException;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.09.04
 */
@Service
public class UserService {

    private SecurityTokenService securityTokenService;

    private SysLoginService sysLoginService;

    private SysValidService sysValidService;
    
    @Autowired
    public UserService(SecurityTokenService securityTokenService,
			SysLoginService sysLoginService, SysValidService sysValidService) {
		super();
		this.securityTokenService = securityTokenService;
		this.sysLoginService = sysLoginService;
		this.sysValidService = sysValidService;
	}

    public SecurityToken saveLogin(LoginFilter filter) {
        SysLogin sysLogin = sysLoginService.getUserByLoginName(filter.getMobile());
        if (sysLogin == null) {
            throw new ServiceException("用户不存在");
        }

        SecurityToken securityToken = new SecurityToken();
        securityToken.setUserId(sysLogin==null?filter.getMobile():sysLogin.getSysId());
        securityToken.setToken(getToken());
        securityTokenService.save(securityToken);
        return securityToken;
    }

	private String getToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }

	public boolean queryByMobile(String mobile) {
		SysLogin sysLogin = sysLoginService.getUserByLoginName(mobile);
		if (sysLogin == null) {
           return false;
        }
		return true;
	}

	public void saveValid(String mobile, String validCode) {
		SysValid sysValid = new SysValid();
		sysValid.setMobile(mobile);
		sysValid.setVaildCode(validCode);
		sysValid.setTimestamp(Long.toString(System.currentTimeMillis()));
		sysValidService.save(sysValid);
	}
	
	public void validCode(LoginFilter filter) {
		SysValid sysValid = sysValidService.getByMobile(filter.getMobile());
		if(ObjectUtils.isBlank(sysValid)){
			throw new ServiceException("该手机号还未获取验证码！");
		}
		if(!StringUtils.equals(filter.getValidCode(), sysValid.getVaildCode())){
			throw new ServiceException("验证码错误！");
		}
		if (System.currentTimeMillis() - Long.parseLong(sysValid.getTimestamp()) > 150000
                || System.currentTimeMillis() - Long.parseLong(sysValid.getTimestamp()) < -150000) {
            throw new ServiceException("验证码已超时，请重新获取！");
        }
		
	}
}
